//------------------------------------------------------------------------------
//  <copyright file="SynchronizedConsumerProducerAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//  </copyright>
//------------------------------------------------------------------------------

namespace Microsoft.Robotics.Runtime
{
    using System;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using System.Threading;

    /// <summary>
    /// A consumer/producer that subscribes to two agents and synchronizes the incoming messages based on their originating timestamps,
    /// within the tolerance window given by the SyncTolerance property.
    /// Synchronization relies on an AgentMessage property called OriginatingTime. 
    /// This property represents the time when the hardware generated the data (e.g. Kinect depth frame) and needs to be carried from agent message to agent message through the pipeline, 
    /// e.g. the LocalMapAgent and the GlobalMapAgent should have the same originating time as the underlying Kinect frame.
    /// </summary>
    /// <typeparam name="TInput1">The first type of input messages accepted by the consumer part of the agent.</typeparam>
    /// <typeparam name="TInput2">The second type of input messages accepted by the consumer part of the agent.</typeparam>
    /// <typeparam name="TOutput">The type of messages published by this agent.</typeparam>
    [DataContract]
    public abstract class SynchronizedConsumerProducerAgent<TInput1, TInput2, TOutput> : ProducerAgent<TOutput>, ISubscriptionReceiver<MessageTuple<TInput1, TInput2>>
        where TInput1 : AgentMessage
        where TInput2 : AgentMessage
        where TOutput : AgentMessage
    {
        /// <summary>
        /// The agent we subscribe to.
        /// </summary>
        private IAgentHost synchronizedJoinAgent;

        /// <summary>
        /// Gets the maximum acceptable delta (in milliseconds) between two messages to be considered in sync.
        /// Any messages that don't have a pair within this window are discarded.
        /// </summary>
        [DataMember(Name = "SyncTolerance")]
        private int syncTolerance;
        
        /// <summary>
        /// Gets a value indicating whether the synchronization queues are allowed to overflow (and dump the oldest messages).
        /// This should be false in most cases. Needs to be true if the two producers generate data at widely different frequencies.
        /// </summary>
        [DataMember(Name = "AllowOverflow")]
        private bool allowOverflow;

        /// <summary>
        /// Initializes a new instance of the SynchronizedConsumerProducerAgent class.
        /// This constructor is not called when the agent is created from a manifest file.
        /// </summary>
        /// <param name="name">A friendly name for this agent instance.</param>
        /// <param name="syncTolerance">
        /// The maximum acceptable delta (in milliseconds) between two messages to be considered in sync. 
        /// If 0, the best pairing is returned, regardless of the delta between them.
        /// </param>
        /// <param name="allowOverflow">True if synchronization queues are allowed to overflow (and dump the oldest messages). This should be false in most cases.</param>
        public SynchronizedConsumerProducerAgent(string name, int syncTolerance, bool allowOverflow = false)
            : base(name)
        {
            this.allowOverflow = allowOverflow;
            this.syncTolerance = syncTolerance;
        }

        /// <summary>
        /// Gets the name of the first producer. Needs to be provided by derived classes.
        /// </summary>
        protected abstract string ProducerName1
        {
            get;
        }

        /// <summary>
        /// Gets the name of the second producer. Needs to be provided by derived classes.
        /// </summary>
        protected abstract string ProducerName2        
        {
            get;
        }

        /// <summary>
        /// Called after construction, to allow the agent to finish initialization. 
        /// </summary>
        /// <param name="locator">A locator that can be used to find other agents.</param>
        public override void Initialize(AgentLocator locator)
        {
            Agent.ValidateParameter(string.IsNullOrEmpty(this.ProducerName1), this.ProducerName1, "KinectAgent");
            Agent.ValidateParameter(string.IsNullOrEmpty(this.ProducerName2), this.ProducerName2, "JointMessageAgent");

            base.Initialize(locator);

            // create the join agent and add it to the agent pipeline, then subscribe to it.
            string syncName = string.Format("{0}(Sync)", this.Name);
            SynchronizationAgent<TInput1, TInput2> syncAgent = new SynchronizationAgent<TInput1, TInput2>(syncName, this.ProducerName1, this.ProducerName2, this.syncTolerance, this.allowOverflow);
            this.synchronizedJoinAgent = locator.Register(syncAgent);
            this.synchronizedJoinAgent.Subscribe(this);
        }

        /// <summary>
        /// Called when the agent transitions from inactive to active.
        /// </summary>
        public override void OnActivated()
        {
            this.synchronizedJoinAgent.Activate();
            base.OnActivated();
        }

        /// <summary>
        /// Called when the agent transitions from active to inactive.
        /// </summary>
        public override void OnDeactivated()
        {
            this.synchronizedJoinAgent.Deactivate();
            base.OnDeactivated();
        }

        /// <summary>
        /// Called when a new input message is available, in this case a combined message containing two synced messages.
        /// </summary>
        /// <param name="message">The combined message to receive.</param>
        public void Receive(MessageTuple<TInput1, TInput2> message)
        {
            this.Receive(message.Message1, message.Message2);
        }

        /// <summary>
        /// Called to process the two messages. 
        /// The messages are guaranteed to be in sync (within the window given by SyncTolerance), based on the originating time of their underlying data.
        /// </summary>
        /// <param name="message1">The message of the first type</param>
        /// <param name="message2">The message of the second type</param>
        protected abstract void Receive(TInput1 message1, TInput2 message2);
    }
}
